package com.kly.user.serviceImpl.traffic.wlm;

import cn.hutool.core.net.NetUtil;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.google.common.base.Splitter;
import com.kly.user.config.NacosValueConfig;
import com.kly.user.db.entity.IssueConfigEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.db.entity.UserWlmEntity;
import com.kly.user.dto.TrafficSourceDto;
import com.kly.user.dto.vo.TrafficSourceReq;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.TrafficSourceEnum;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class PPWLM extends WLMBase {
    @Resource
    NacosValueConfig nacosValueConfig;
    private String localIP = NetUtil.getLocalhostStr();


    @PostConstruct
    public void init() {
        WLMTrafficHandler.wlmBaseMap.put(AppEnum.PP.getUserAppFlag(), this);
    }


    @Override
    public void dealCondition(IssueConfigEntity issueConfigEntity, UserEntity userEntity) {
        Integer wlmAmount = wlmAmount(userEntity.getUserCode());
        logger.info("==WLMIssueTask=={},userCode:{},name:{},当日已经下发:{}", localIP, userEntity.getUserCode(), userEntity.getNickName(), wlmAmount);
        if (wlmAmount >= issueConfigEntity.getIssueCount()) {
            logger.info("==WLMIssueTask 当前用户的当日wlm下发次数已经足够==,userCode:{},name:{}", userEntity.getUserCode(), userEntity.getNickName());
            return;
        }

        boolean online = userEntity.getOnline() == 1;
        //在线
        if (online) {
            int issueTime = getWLMIssueTime(issueConfigEntity, wlmAmount);
            logger.info("==WLMIssueTask 在线==,userCode:{},name:{},下次应该下发的时间mins是:{}", userEntity.getUserCode(), userEntity.getNickName(), issueTime);
            push(issueConfigEntity, wlmAmount, userEntity, issueTime);
            return;
        }

        logger.info("==WLMIssueTask 不在线==,userCode:{},name:{}", userEntity.getUserCode(), userEntity.getNickName());
        if (isToday(userEntity.getGmtModified())) {
            logger.info("==WLMIssueTask 不在线 但今天有启动过==,userCode:{},name:{}", userEntity.getUserCode(), userEntity.getNickName());
            //当天wlm数量
            //距离上次下发时间
            int IssueTime = wlmAmount * issueConfigEntity.getIssueHour();
            push(issueConfigEntity, wlmAmount, userEntity, IssueTime);
        } else {
            logger.info("==WLMIssueTask 不在线 但今天没有启动过==,userCode:{},name:{}", userEntity.getUserCode(), userEntity.getNickName());
            SimpleDateFormat format0 = new SimpleDateFormat("HHmmss");
            Time time = new Time(new Date().getTime());
            if (Integer.parseInt(format0.format(issueConfigEntity.getIssueTime())) < Integer.parseInt(format0.format(time))) {
                int IssueTime = wlmAmount * issueConfigEntity.getIssueHour();
                push(issueConfigEntity, wlmAmount, userEntity, IssueTime);
            }
        }
    }


    public void push(IssueConfigEntity issueConfigEntity, Integer wlmAmount, UserEntity userEntity, int issueTime) {
        if (wlmAmount == 0) {
            logger.info("==WLMIssueTask 今日无下发==,userCode:{},name:{},今日无下发", userEntity.getUserCode(), userEntity.getNickName());
            String userCode = getIssueUserCode(userEntity);
            if (userCode == null) {
                logger.info("==WLMIssueTask 今日无下发==,userCode:{},name:{},找不到目标model", userEntity.getUserCode(), userEntity.getNickName());
                return;
            }
            logger.info("==WLMIssueTask 今日无下发 找到 目标model==,userCode:{},name:{},model:{}", userEntity.getUserCode(), userEntity.getNickName(), userCode);
            addUserWlm(userEntity.getUserCode(), userCode, userEntity.getAppCode());
            return;
        }

        logger.info("==WLMIssueTask 今日有下发==,userCode:{},name:{},今日无下发", userEntity.getUserCode(), userEntity.getNickName());
        if (wlmAmount < issueConfigEntity.getIssueCount()) {
            long distanceWLMTime = distanceWLMTime(userEntity.getUserCode());
            if (distanceWLMTime > issueTime) {
                //下发
                String userCode = getIssueUserCode(userEntity);
                if (userCode != null) {
                    addUserWlm(userEntity.getUserCode(), userCode, userEntity.getAppCode());
                }
            }
        }
    }


    public String getIssueUserCode(UserEntity userEntity) {
        TrafficSourceReq req = TrafficSourceReq.builder()
                .userCode(userEntity.getUserCode())
                .appCode(userEntity.getAppCode())
                .mobile(userEntity.getMobile())
                .email(userEntity.getEmail())
                .build();
        Response<TrafficSourceDto> resp = userTrafficSourceService.getTrafficSource(req);
        if (!resp.isSuccess() || resp.getData() == null) {
            return null;
        }

        // 如果开关关闭，一律走非自然流量策略；如果开关开启，自然流量走自然流量策略
        boolean isWhiteUser = resp.getData().getWhiteFlag() == 1;

        boolean isOrganic = TrafficSourceEnum.Organic.equals(resp.getData().getTrafficSourceEnum());
        if (isOrganic || isWhiteUser) {
            if (StringUtils.isEmpty(ppWlmIssueFixUserCode)) {
                return null;
            }
            // 指定的用户
            String targetUser = null;
            List<String> allUsers = Splitter.on(",").splitToList(nacosValueConfig.ppWlmIssueFixUserCode());
            List<String> onlineUsers = nacosValueConfig.keepOnlineUserCodes();

            final List<UserWlmEntity> wlmList = userWlmDao.listUserWlmList(allUsers, userEntity.getUserCode());
            final List<String> hasWlmUsers = wlmList.parallelStream().map(UserWlmEntity::getUserCode).collect(Collectors.toList());
            List<String> noWlmUsers = new ArrayList<>();

            //找到没有关系的指定user
            allUsers.forEach(u -> {
                if (!hasWlmUsers.contains(u)) {
                    noWlmUsers.add(u);
                }
            });

            //找到没有关系的指定的 在线的user
            for (String t : noWlmUsers) {
                if (onlineUsers.contains(t)) {
                    targetUser = t;
                    break;
                }
            }

            //找不到在线的，就找离线的
            if (targetUser == null) {
                if (!CollectionUtils.isEmpty(noWlmUsers)) {
                    targetUser = noWlmUsers.get(0);
                }
            }

            //找到了就返回可用的user ，最终找不到就直接返回null
            return targetUser;

        }

        return getUser(userEntity.getUserCode(), userEntity.getLookingFor(), false);
    }

    public static void main(String[] args) {

    }


}
